package com.las.bot.cmd.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.las.bot.dao.GroupUserDao;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseNonCommand;
import com.las.common.Constant;
import com.las.utils.mirai.CmdUtil;
import com.las.utils.mirai.MiRaiUtil;
import com.model.GroupUser;
import com.utils.JsonUtils;
import com.utils.ThreadUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

//@BotCmd(funName = "群广告屏蔽", isMatch = false)
public class AdvCloseCmd extends BaseNonCommand {

    private static Logger logger = Logger.getLogger(AdvCloseCmd.class);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private GroupUserDao groupUserDao;

    public AdvCloseCmd() {
        super("群广告屏蔽", "GC");
    }

    @Override
    public void execute(JSONObject obj, Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        if (command.equals("群广告屏蔽") || command.equals("GC")) {
            return;
        }
        if (Constant.MESSAGE_TYPE_GROUP == type) {
            GroupUser gu = groupUserDao.findByGIdUId(id, userId);
            if (ObjectUtil.isNull(gu)) {
                List<JSONObject> groupUserList = MiRaiUtil.getInstance().getGroupUsers(id);
                AtomicBoolean tag = new AtomicBoolean(false);
                groupUserList.parallelStream().forEach(object -> {
                    logger.info("获得群员信息：" + JsonUtils.getJsonString(object));
                    Long qq = object.getLong("id");
                    String permission = object.getString("permission");
                    GroupUser groupUser = new GroupUser();
                    groupUser.setGroupId(id);
                    groupUser.setUserId(qq);
                    groupUser.setPermission(permission);
                    if (userId.equals(qq)) {
                        if (!permission.equalsIgnoreCase("MEMBER")) {
                            tag.set(true);
                        }
                    }
                    groupUserDao.saveOrUpdate(groupUser);
                });
                if (tag.get()) {
                    return;
                }
            } else {
                // 管理员和群主可以不用屏蔽广告（也就是群主可以光明正大发广告）
                if (!gu.getPermission().equalsIgnoreCase("MEMBER")) {
                    return;
                }
            }
            JSONArray msgChain = obj.getJSONArray("messageChain");
            if (CollectionUtil.isNotEmpty(msgChain)) {
                Long msgId = null;
                for (int i = 0; i < msgChain.size(); i++) {
                    JSONObject jsonObject = msgChain.getJSONObject(i);
                    String msgType = jsonObject.getString("type");
                    if ("Source".equals(msgType)) {
                        msgId = jsonObject.getLong("id");
                        break;
                    }
                }
                if (ObjectUtil.isNotNull(msgId)) {
                    Long finalMsgId = msgId;
                    executor.execute(() -> {
                        Map<String, String> info = new HashMap<>();
                        info.put("grant_type", "client_credentials");
                        info.put("client_id", "Pp81KdwxQxkCwYH6Sy4zjyUa");
                        info.put("client_secret", "3nxhba0OWrpHsLOPkXbRWNIQAcf0uKbN");
                        String result = HttpKit.post("https://aip.baidubce.com/oauth/2.0/token", info, null);
                        JSONObject object = JsonUtils.getJsonObjectByJsonString(result);
                        String token = object.getString("access_token");

                        info = new HashMap<>();
                        info.put("access_token", token);
                        info.put("text", command);
                        String result2 = HttpKit.post("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined", info, null);
                        logger.info("广告屏蔽判定结果：" + result2);
                        JSONObject object2 = JsonUtils.getJsonObjectByJsonString(result2);
                        String judge = object2.getString("conclusion");

                        String msg = "判定是：" + judge;
                        Double v = null;
                        boolean tag = false;
                        if ("不合规".equals(judge) || "疑似".equals(judge)) {
                            JSONArray jsonArray = object2.getJSONArray("data");
                            v = jsonArray.getJSONObject(0).getJSONArray("hits").getJSONObject(0).getDouble("probability");
                            String data = String.format("%.2f", v * 100) + "%";
                            msg = msg + "\n违规原因：" + object2.getJSONArray("data").getJSONObject(0).getString("msg");
                            msg = msg + "\n鉴定值：" + data;
                        }
                        logger.info("判定结果是：" + msg);

                        if ("不合规".equals(judge) || "疑似".equals(judge)) {
                            String config = "0.9#是";
                            String[] split = config.split("#");
                            double limit = Double.parseDouble(split[0]);
                            if (split[1].equals("是")) {
                                tag = true;
                            }
                            if (null != v && v > limit) {
                                sendJudge90Msg(finalMsgId, msg, userId, id, tag, command);
                            } else {
                                // 0.2是定制的，不许改
                                if (null != v && v > 0.2) {
                                    sendJudge20Msg(msg, userId, id, command);
                                }
                            }
                        }
                    });
                }
            }
        }
    }

    private void sendJudge90Msg(Long msgId, String msg, Long userId, Long id, boolean tag, String cmd) {
        if (tag) {
            if (msg.contains("恶意推广") && cmd.length() > 10) {
                //MiRaiUtil.getInstance().mute(id, userId, 60);
                MiRaiUtil.getInstance().reCall(msgId);
                CmdUtil.sendAtMessage(msg, userId, userId, id, com.las.common.Constant.MESSAGE_TYPE_GROUP);
            }
        }

    }


    private void sendJudge20Msg(String msg, Long userId, Long id, String cmd) {
//        if (msg.contains("恶意推广")) {
//            if (cmd.length() > 10) {
//                // 禁言1分钟
//                MiRaiUtil.getInstance().mute(id, userId, 60);
//                CmdUtil.sendAtMessage(msg, userId, userId, id, com.las.common.Constant.MESSAGE_TYPE_GROUP);
//            }
//        }
    }


}
